package com.bt7274.controller;

import com.bt7274.grace.result.GraceJSONResult;
import com.bt7274.pojo.UserExp;
import com.bt7274.pojo.bo.UserQueryParam;
import com.bt7274.pojo.vo.PageResult;
import com.bt7274.pojo.vo.UserInfoVO;
import com.bt7274.service.AdminService;
import com.bt7274.service.UserExpService;
import com.bt7274.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

/**
 * 管理员用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/user")
@Tag(name = "管理员用户管理", description = "管理员对用户的管理操作")
public class  AdminUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserExpService userExpService;

    @Autowired
    private AdminService adminService;

    /**
     * 更新用户权限组
     */
    @PutMapping("/permission/{userId}")
    @Operation(summary = "更新用户权限组", description = "管理员更新指定用户的权限组等级")
    public GraceJSONResult updatePermissionGroup(@PathVariable String userId,
                                                 @RequestParam Integer permissionGroup,
                                                 HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdmin(request)) {
                return GraceJSONResult.errorMsg("没有管理员权限");
            }

            boolean success = userService.updatePermissionGroup(userId, permissionGroup);
            if (success) {
                String adminId = getAdminId(request);
                log.info("管理员(ID:{})更新用户权限组成功，用户ID: {}, 新等级: {}",
                        adminId, userId, permissionGroup);
                return GraceJSONResult.ok("更新用户权限组成功");
            } else {
                return GraceJSONResult.errorMsg("更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户权限组失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 封禁用户
     */
    @PutMapping("/ban/{userId}")
    @Operation(summary = "封禁用户", description = "管理员封禁指定用户")
    public GraceJSONResult banUser(@PathVariable String userId, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdmin(request)) {
                return GraceJSONResult.errorMsg("没有管理员权限");
            }

            boolean success = userService.banUser(userId);
            if (success) {
                String adminId = getAdminId(request);
                log.info("管理员(ID:{})封禁用户成功，用户ID: {}", adminId, userId);
                return GraceJSONResult.ok("用户封禁成功");
            } else {
                return GraceJSONResult.errorMsg("封禁失败");
            }
        } catch (Exception e) {
            log.error("封禁用户失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 解封用户
     */
    @PutMapping("/unban/{userId}")
    @Operation(summary = "解封用户", description = "管理员解封指定用户")
    public GraceJSONResult unbanUser(@PathVariable String userId, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdmin(request)) {
                return GraceJSONResult.errorMsg("没有管理员权限");
            }

            boolean success = userService.unbanUser(userId);
            if (success) {
                String adminId = getAdminId(request);
                log.info("管理员(ID:{})解封用户成功，用户ID: {}", adminId, userId);
                return GraceJSONResult.ok("用户解封成功");
            } else {
                return GraceJSONResult.errorMsg("解封失败");
            }
        } catch (Exception e) {
            log.error("解封用户失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 调整用户BT币
     */
    @PutMapping("/bt/{userId}")
    @Operation(summary = "调整用户BT币", description = "管理员调整指定用户的BT币数量")
    public GraceJSONResult adjustUserBt(@PathVariable String userId,
                                        @RequestParam Integer btDelta,
                                        @RequestParam(required = false) String reason,
                                        HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdmin(request)) {
                return GraceJSONResult.errorMsg("没有管理员权限");
            }

            boolean success = userExpService.updateBt(userId, btDelta);
            if (success) {
                String adminId = getAdminId(request);
                log.info("管理员(ID:{})调整用户BT币成功，用户ID: {}, 变动量: {}, 原因: {}",
                        adminId, userId, btDelta, reason);
                return GraceJSONResult.ok("BT币调整成功");
            } else {
                return GraceJSONResult.errorMsg("调整失败");
            }
        } catch (Exception e) {
            log.error("调整用户BT币失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 调整用户经验值
     */
    @PutMapping("/experience/{userId}")
    @Operation(summary = "调整用户经验值", description = "管理员调整指定用户的经验值")
    public GraceJSONResult adjustUserExperience(@PathVariable String userId,
                                                @RequestParam Integer experienceDelta,
                                                @RequestParam(required = false) String reason,
                                                HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdmin(request)) {
                return GraceJSONResult.errorMsg("没有管理员权限");
            }

            boolean success = userExpService.updateExperience(userId, experienceDelta);
            if (success) {
                String adminId = getAdminId(request);
                log.info("管理员(ID:{})调整用户经验值成功，用户ID: {}, 变动量: {}, 原因: {}",
                        adminId, userId, experienceDelta, reason);
                return GraceJSONResult.ok("经验值调整成功");
            } else {
                return GraceJSONResult.errorMsg("调整失败");
            }
        } catch (Exception e) {
            log.error("调整用户经验值失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 获取用户详细信息（管理员视图）
     */
    @GetMapping("/detail/{userId}")
    @Operation(summary = "获取用户详细信息", description = "管理员获取用户的完整信息")
    public GraceJSONResult getUserDetail(@PathVariable String userId, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdmin(request)) {
                return GraceJSONResult.errorMsg("没有管理员权限");
            }

            UserInfoVO userInfo = userService.getUserInfo(userId);
            UserExp userExp = userExpService.getUserExp(userId);

            UserDetailVO detail = new UserDetailVO();
            detail.setUserInfo(userInfo);
            detail.setUserExp(userExp);

            return GraceJSONResult.ok(detail);
        } catch (Exception e) {
            log.error("获取用户详细信息失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 查询用户列表
     */
    @GetMapping("/list")
    @Operation(summary = "查询用户列表", description = "管理员查询用户列表")
    public GraceJSONResult listUsers(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) Integer permissionGroup,
            @RequestParam(required = false) Integer status,
            HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdmin(request)) {
                return GraceJSONResult.errorMsg("没有管理员权限");
            }

            // 构建查询条件
            UserQueryParam param = new UserQueryParam();
            param.setPageNum(current);
            param.setPageSize(size);
            param.setUsername(username);
            param.setEmail(email);
            param.setPermissionGroup(permissionGroup);
            param.setStatus(status);

            // 查询用户列表
            PageResult<UserInfoVO> pageResult = userService.queryUserList(param);
            return GraceJSONResult.ok(pageResult);
        } catch (Exception e) {
            log.error("查询用户列表失败: {}", e.getMessage(), e);
            return GraceJSONResult.errorMsg(e.getMessage());
        }
    }

    /**
     * 验证是否为管理员
     */
    private boolean validateAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return false;
        }

        String adminId = (String) session.getAttribute("adminId");
        Boolean isAdmin = (Boolean) session.getAttribute("isAdmin");

        if (adminId == null || isAdmin == null || !isAdmin) {
            return false;
        }

        // 调用管理员服务验证管理员权限
        return adminService.checkAdminPermission(adminId);
    }

    /**
     * 获取管理员ID
     */
    private String getAdminId(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return null;
        }
        return (String) session.getAttribute("adminId");
    }

    /**
     * 用户详细信息VO
     */
    @lombok.Data
    public static class UserDetailVO {
        private UserInfoVO userInfo;
        private UserExp userExp;
    }
}